<template>
  <!-- 权限设置 -->
  <a-modal
    v-model:open="visible"
    :title="`权限设置`"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="850"
    @cancel="cancel"
    centered
  >
    <a-divider style="margin: 12px 0" />
    <a-spin :spinning="menuLoading">
    <div expandIconPosition="end" :bordered="false">
      <template v-for="item in menuData" :key="item.key">
        <NestedCollapse
          :menuItem="item"
          :showDataPermi="showDataPermi"
          @changeAuth="changeAuth"
        />
      </template>
    </div>
    </a-spin>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>
import { MENU_AUTH } from "@/constants/stationConfig"
import NestedCollapse from "./nestedCollapse.vue"
const $api = inject("$api");
const props = defineProps({
  authConfigVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  defaultIds: {
    type: Array,
    default: () => [],
  },
  disabledIds: {
    type: Array,
    default: () => [],
  },
  showDataPermi: {
    type: Boolean,
    default: true,
  },
});
const loading = ref(false);
const visible = ref(props.authConfigVisible);
const selectIds = ref([]);
const emits = defineEmits(["update:authConfigVisible"]);
const menuLoading = ref(false);
const getBaseMenuList = async () => {
  const parmas = {
    menuType: MENU_AUTH.menu,
    all: 1 // 权限这里需要拉全量菜单
  }
  menuLoading.value = true
  const res = await $api.baseMenuList(parmas);
  menuLoading.value = false
  if (res && res.code === 0) {
    menuData.value = res.data;
  }
};
watch(
  () => props.authConfigVisible,
  async (val) => {
    visible.value = val;
    if (val) {
      await getBaseMenuList();
      selectIds.value = props.defaultIds;
      const addNameField = (menu) => {
        // 遍历每个菜单项
        menu.forEach((item) => {
          item.header = item.name;
          item.key = item.permission;

          if (props.isEdit && props.defaultIds?.includes(item.id)) {
            item.checked = true;
          } else {
            item.checked = false;
          }
          if (props.disabledIds?.includes(item.id)) {
            item.disabled = true;
          } else {
            item.disabled = false;
          }
          // 如果有子菜单项
          if (item.children && item.children.length > 0) {
            addNameField(item.children);
          }
          // 如果有子菜单项
          if (item.btnList && item.btnList.length > 0) {
            addNameField(item.btnList);
          }
          if (item.dataPermissionList && item.dataPermissionList.length > 0) {
            addNameField(item.dataPermissionList);
          }
        });
      };
      addNameField(menuData.value);
    }
  }
);
const menuData = ref([]);
const cancel = () => {
  emits("update:authConfigVisible", false);
  menuData.value = [];
  selectIds.value = [];
};
// 获取当前选中权限的id列表
let result = []
const findChildrenIds = (data) => {
  if (!data || !data.length) {
    return;
  }
  for (let i = 0, len = data.length; i < len; i++) {
    const childs = data[i].children;
    result.push(data[i].id);
    if (childs && childs.length > 0) {
      findChildrenIds(childs);
    }
  }
  return result;
};
// 获取当前选中权限的对象数据
let objRes = {};
const findCheckObj = (data, id) => {
  if (!data || !data.length) {
    return;
  }
  for (let i = 0, len = data.length; i < len; i++) {
    const childs = data[i].children;
    if(data[i].id === id){
      objRes = data[i]
    }
    if (childs && childs.length > 0) {
      findCheckObj(childs, id);
    }
  }
  return objRes;
};
const changeAuth = (data) => {
  const childrenData = findCheckObj(menuData.value, data.id)
  result = []
  const childIds = findChildrenIds(childrenData.children) || [];
  if (data.checked) {
    selectIds.value.push(data.id, ...childIds);
  } else {
    selectIds.value = selectIds.value.filter(
      (id) => id !== data.id && !childIds.includes(id)
    );
  }
  selectIds.value = [...new Set(selectIds.value)];
  const traverse = (arr) => {
    for (const item of arr) {
      if (selectIds.value.includes(item.id)) {
        item.checked = true; // 更新 checked 属性
      } else {
        item.checked = false;
      }
      if (item.children && Array.isArray(item.children)) {
        traverse(item.children);
      }
    }
  };
  traverse(menuData.value);
};

const handleSubmit = async () => {
  emits("changeAuth", selectIds.value);
  await nextTick();
  emits("update:authConfigVisible", false);
  // cancel();
};

onMounted(async () => {
});
</script>

<style lang="less" scoped>
.footerBar {
  text-align: center;
  margin-top: 30px;
}
</style>